<#
.SYNOPSIS
 Modifies AssemblyFileVersion and ProductVersion for projects using Biztalk Deployment Framework (BTDF)
 
.PARAMETER Disable
  Convenience switch to disable changes to files (used for test purposes)
#>

# Enable -Verbose option
[CmdletBinding()]

param(
	[switch]$Disable,
	[string]$pathToSearch = $env:TF_BUILD_SOURCESDIRECTORY,
	[string]$buildNumber = $env:TF_BUILD_BUILDNUMBER,
	[string]$buildUri = $env:TF_BUILD_BUILDURI,
	[string]$DeploymentFile = "*Deployment.btdfproj",
	[bool]$UpdateProductId = $true,
	[bool]$UpdatePackageComments = $true
)

if ($PSBoundParameters.ContainsKey('Disable'))
{
	Write-Verbose "Script disabled; no actions will be taken on the files."
}

if ($buildUri -match "(?<=.build.build.).*" -ne $true) 
{
	Write-Output "Invalid builduri: $buildUri"
}
else
{
  # Uncomment to use build ID insted of build number.
  $buildId = $Matches[0]
	$versionToUse = "1.0.0.$buildId"
	
	# Update MSI package
	gci -Path $pathToSearch -Filter $DeploymentFile -Recurse | %{
		Write-Output "  -> Changing $($_.FullName)" 

		[xml]$content = gc $_.FullName
		$tt = $content.Project.PropertyGroup | where { $_.ProductVersion -ne $null }
		if ($tt -ne $null)
		{
			$tt.ProductVersion = ($tt.ProductVersion + "." + $buildId)
			$versionToUse = $tt.ProductVersion
			if ($UpdatePackageComments) {$tt.PackageComments = ($tt.PackageComments + " (" + $buildNumber + ")")}
			if ($UpdateProductId) {$tt.ProductId = [System.Guid]::NewGuid().toString()}
			if(-not $Disable) 
			{ 
				sp $_.FullName IsReadOnly $false # remove the read-only bit on the file
				$content.Save($_.FullName)
			}
		}
		else
		{
			Write-Output "ProductVersion not found in file"
		}
	}

	# Update AssemblyInfo
	$AssemblyFileVersionPattern = '(?<=AssemblyFileVersion\(").*(?="\))'
	$AssemblyConfigurationPattern = '(?<=AssemblyConfiguration\(").*(?="\))'
	gci -Path $pathToSearch -Filter "assemblyinfo.*" -Recurse | %{
		Write-Output "  -> Changing $($_.FullName)" 
		
		if(-not $Disable) 
		{ 		
			# remove the read-only bit on the file
			sp $_.FullName IsReadOnly $false

			(gc $_.FullName) | % { $_ -replace $AssemblyFileVersionPattern, $versionToUse  } | sc $_.FullName
			(gc $_.FullName) | % { $_ -replace $AssemblyConfigurationPattern, $buildNumber } | sc $_.FullName
		}
	 }
}